<template>
  <div class="equipment-container">
    <!-- 页面标题 -->
    <h3 class="page-title">设备信息</h3>

    <!-- 操作按钮区域 -->
    <div class="operation-bar">
      <el-button type="primary" class="add-btn">+ 添加设备</el-button>
      
      <!-- 筛选区域 -->
      <div class="filter-area">
        <el-select 
          v-model="queryParams.statusVo" 
          placeholder="设备状态" 
          class="filter-select"
        >
          <el-option label="全部" value=""></el-option>
          <el-option label="未审核" value="0"></el-option>
          <el-option label="已上架" value="1"></el-option>
          <el-option label="已下架" value="2"></el-option>
          <el-option label="已成交" value="3"></el-option>
        </el-select>
        
        <!-- 树形选择器替换原下拉框 -->
        <el-tree-select
          v-model="queryParams.emparentIdVo"
          :data="typeTreeData"
          :props="treeProps"
          placeholder="设备类型"
          class="filter-select"
          @change="handleParentTypeChange"
          clearable
          :render-after-expand="false"
        ></el-tree-select>
        
        <el-input 
          v-model="queryParams.brandVo" 
          placeholder="关键字" 
          class="search-input"
          @keyup.enter="getEquipmentList"
        ></el-input>
        
        <el-button type="primary" @click="getEquipmentList">搜索</el-button>
      </div>
    </div>

    <!-- 设备表格 -->
<el-table 
  :data="equipmentList" 
  border 
  stripe 
  class="equipment-table"
  v-loading="loading"
  element-loading-text="加载中..."
>
  <!-- 保留选择列：宽度固定 -->
  <el-table-column type="selection" width="50"></el-table-column>
  <el-table-column prop="equipmentId" label="ID" width="80"></el-table-column>
  
  <!-- 类型品牌列：最小宽度 + 自适应 -->
  <el-table-column label="类型品牌" min-width="80">
    <template #default="scope">
      <div>
        <div>{{ getEquipmentTypeName(scope.row.typeId) }}-{{ scope.row.brand }}</div>
        <div class="small-text">{{ scope.row.model }}</div>
      </div>
    </template>
  </el-table-column>
  
  <!-- 头图列：宽度固定 -->
  <el-table-column label="头图" width="100">
    <template #default="scope">
      <el-image 
        v-if="scope.row.equipmentImages && scope.row.equipmentImages.length > 0"
        :src="scope.row.equipmentImages[0].imageUrl" 
        fit="cover"
        class="head-image"
        fallback-src="https://picsum.photos/80/60"
      ></el-image>
      <div v-else class="empty-image"></div>
    </template>
  </el-table-column>
  
  <!-- 标题列：最小宽度 + 自适应（占主要空间） -->
  <el-table-column label="标题" min-width="150">
    <template #default="scope">
      <div>
        <div class="title-main">出售{{ scope.row.year }}年{{ scope.row.brand }}{{ scope.row.verticalHeight }}米{{ getEquipmentTypeName(scope.row.typeId) }}</div>
        <div class="small-text">设备位置: {{ scope.row.location || '-' }}</div>
        <div class="small-text">产生时间: {{ formatTime(scope.row.releaseTime) }}</div>
        <div class="small-text">更新时间: {{ formatTime(scope.row.updateTime) }}</div>
      </div>
    </template>
  </el-table-column>
  
  <!-- 价格列：宽度固定 -->
  <el-table-column label="价格(万)" width="90">
    <template #default="scope">
      <div class="price-text">{{ (scope.row.price / 10000).toFixed(2) }} 万</div>
    </template>
  </el-table-column>
  
  <!-- 出厂年份列：宽度固定 -->
  <el-table-column prop="year" label="出厂年份" width="90"></el-table-column>
  <!-- 联系人列：宽度固定 -->
  <el-table-column prop="contactName" label="联系人" width="70">
    <template #default="scope">
      <div class="contact-name">{{ scope.row.contactName || '-' }}</div>
    </template>
  </el-table-column>
  <!-- 业务员列：宽度固定 -->
  <el-table-column label="业务员" width="90">
    <template #default="scope">
      <div>{{ scope.row.salesman || '未知' }}</div>
    </template>
  </el-table-column>
  <!-- 审核列：宽度固定 -->
  <el-table-column label="审核" width="110">
    <template #default="scope">
      <div class="status-group">
        <span :class="scope.row.status === 0 ? 'status-unaudit' : 'status-audited'">
          {{ scope.row.status === 0 ? '未审核' : '已审核' }}
        </span>
        <el-button 
          v-if="scope.row.status === 0"
          type="text" 
          size="small" 
          class="operate-btn"
          @click="handleAudit(scope.row)"
        >
          审核
        </el-button>
      </div>
    </template>
  </el-table-column>
  <!-- 上下架列：宽度固定 -->
  <el-table-column label="上下架" width="110">
    <template #default="scope">
      <div class="status-group">
        <span :class="scope.row.status === 1 ? 'status-online' : 'status-offline'">
          {{ scope.row.status === 1 ? '已上架' : '已下架' }}
        </span>
        <el-button 
          v-if="scope.row.status === 1 || scope.row.status === 2"
          type="text" 
          size="small" 
          class="operate-btn"
          :class="scope.row.status === 1 ? 'text-offline' : 'text-online'"
          @click="handleShelf(scope.row)"
        >
          {{ scope.row.status === 1 ? '下架' : '上架' }}
        </el-button>
      </div>
    </template>
  </el-table-column>
  <!-- 操作列：宽度固定 -->
  <el-table-column label="操作" width="180">
    <template #default="scope">
      <div class="operation-buttons">
        <el-button type="text" size="small" class="text-detail" @click="handleDetail(scope.row)">查看详细</el-button>
        <el-button type="text" size="small" class="text-price" @click="handlePriceList(scope.row)">砍价列表</el-button>
      </div>
    </template>
  </el-table-column>
</el-table>

    <!-- 审核模态框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="设备审核"
      width="550px"
      :before-close="closeAuditDialog"
      destroy-on-close
    >
      <!-- 审核模态框内容保持不变 -->
      <el-form 
        ref="auditFormRef" 
        :model="auditForm" 
        label-width="130px"
        :rules="auditFormRules"
        class="audit-form"
      >
        <el-form-item label="设备信息" class="equipment-info-item">
          <div class="equipment-info">
            <span class="info-label">设备ID：</span>{{ currentEquipment?.equipmentId || '-' }}
            <span class="info-label">品牌型号：</span>{{ currentEquipment?.brand || '-' }}-{{ currentEquipment?.model || '-' }}
            <span class="info-label">发布时间：</span>{{ formatTime(currentEquipment?.releaseTime) || '-' }}
          </div>
        </el-form-item>

        <el-form-item label="审核结果" prop="auditResult">
          <el-radio-group v-model="auditForm.auditResult" @change="handleAuditResultChange">
            <el-radio label="pass" border>审核通过（自动上架）</el-radio>
            <el-radio label="reject" border>审核不通过（不上架）</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item 
          label="审核备注" 
          prop="auditRemark"
          :required="auditForm.auditResult === 'reject'"
        >
          <el-input
            type="textarea"
            v-model="auditForm.auditRemark"
            placeholder="审核不通过时需说明原因"
            rows="3"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeAuditDialog">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>

    <!-- 分配业务员模态框 -->
    <el-dialog
      v-model="allocateDialogVisible"
      title="分配业务员"
      width="500px"
      :before-close="closeAllocateDialog"
      destroy-on-close
    >
      <!-- 搜索区域 -->
      <div class="allocate-search">
        <el-input
          v-model="businessmanQuery.keyword"
          placeholder="输入用户名或姓名搜索"
          class="search-input"
          @keyup.enter="getBusinessmanList"
        >
          <template #append>
            <el-button type="primary" @click="getBusinessmanList">查找</el-button>
          </template>
        </el-input>
      </div>

      <!-- 业务员列表 -->
      <el-table
        :data="businessmanList"
        border
        v-loading="businessmanLoading"
        element-loading-text="加载中..."
        class="businessman-table"
      >
        <el-table-column label="姓名" prop="name" width="350"></el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="confirmAllocate(scope.row)"
            >
              选择分配
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="businessman-pagination">
        <el-pagination
          v-model:current-page="businessmanPagination.currentPage"
          v-model:page-size="businessmanPagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="businessmanPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleBusinessmanSizeChange"
          @current-change="handleBusinessmanCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="closeAllocateDialog">取消</el-button>
      </template>
    </el-dialog>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 砍价列表模态框 -->
    <el-dialog
      v-model="bargainDialogVisible"
      title="设备砍价列表"
      width="800px"
      :before-close="closeBargainDialog"
      destroy-on-close
    >
      <!-- 砍价列表 -->
      <el-table
        :data="bargainList"
        border
        v-loading="bargainLoading"
        element-loading-text="加载中..."
        class="bargain-table"
        style="width: 100%"
      >
        <el-table-column prop="bargainId" label="砍价ID" width="100"></el-table-column>
        <el-table-column prop="equipmentId" label="设备ID" width="100"></el-table-column>
        <el-table-column label="设备原价" width="120">
          <template #default="scope">
            {{ (scope.row.originalPrice / 10000).toFixed(2) }} 万元
          </template>
        </el-table-column>
        <el-table-column label="砍价金额(万)" width="120">
          <template #default="scope">
            {{ (scope.row.intentionPrice / 10000).toFixed(2) }} 万元
          </template>
        </el-table-column>
        <el-table-column prop="bargainRemark" label="砍价备注" min-width="200"></el-table-column>
        <el-table-column label="砍价状态" width="120">
          <template #default="scope">
            <span :class="getBargainStatusClass(scope.row.bargainStatus)">
              {{ getBargainStatusText(scope.row.bargainStatus) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="提交时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 空数据提示 -->
      <div v-if="!bargainLoading && bargainList.length === 0" class="empty-bargain">
        <el-empty description="暂无该设备的砍价记录"></el-empty>
      </div>

      <!-- 分页组件 -->
      <div class="bargain-pagination" style="margin-top: 15px; text-align: right;">
        <el-pagination
          v-model:current-page="bargainPagination.currentPage"
          v-model:page-size="bargainPagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="bargainPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleBargainSizeChange"
          @current-change="handleBargainCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="closeBargainDialog">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ArrowDown } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import httpInstance from '../../utils/http';
import router from '@/router';

// 设备列表数据
const equipmentList = ref([]);
// 设备类型树形数据
const typeTreeData = ref([]);
// 树形选择器配置
const treeProps = {
  children: 'children',
  label: 'typeName',
  value: 'typeId'
};

// 加载状态
const loading = ref(false);

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
});

// 查询参数
const queryParams = reactive({
  brandVo: '',
  emparentIdVo: '',
  emsonIdVo: '',
  statusVo: '',
});

// 审核模态框相关数据
const auditDialogVisible = ref(false);
const auditFormRef = ref();
const currentEquipment = ref(null);

// 审核表单数据
const auditForm = reactive({
  auditResult: 'pass',
  auditRemark: '',
});

// 审核表单验证规则
const auditFormRules = {
  auditRemark: [
    { required: true, message: '请输入审核备注', trigger: 'blur' }
  ],
  businessmanId: [
    { required: true, message: '请选择检测员', trigger: 'change' }
  ],
  appearanceDetection: [
    { required: true, message: '请输入外观检测结果', trigger: 'blur' }
  ],
  componentFunctionDetection: [
    { required: true, message: '请输入部件功能检测结果', trigger: 'blur' }
  ],
  performanceParameterDetection: [
    { required: true, message: '请输入性能参数检测结果', trigger: 'blur' }
  ],
  detectionConclusion: [
    { required: true, message: '请输入检测结论', trigger: 'blur' }
  ]
};

// 分配业务员相关数据
const allocateDialogVisible = ref(false);
const currentAllocateEquipment = ref(null);
const businessmanList = ref([]);
const businessmanLoading = ref(false);
const businessmanQuery = reactive({
  keyword: ''
});
const businessmanPagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0
});

// 所有业务员列表
const allBusinessmanList = ref([]);

// 获取设备类型名称
const getEquipmentTypeName = (typeId) => {
  if (!typeId) return '未知类型';
  const findTypeName = (nodes, id) => {
    for (const node of nodes) {
      if (node.typeId === id) {
        return node.typeName;
      }
      if (node.children && node.children.length > 0) {
        const result = findTypeName(node.children, id);
        if (result) return result;
      }
    }
    return null;
  };
  
  const typeName = findTypeName(typeTreeData.value, typeId);
  return typeName || '未知类型';
};

// 页面加载时获取数据
onMounted(() => {
  getEquipmentList();
  getTypeTreeData();
  getAllBusinessman(); // 获取所有业务员数据
});

// 获取设备列表数据
const getEquipmentList = async () => {
  loading.value = true;
  try {
    const eqVo = {
      brand: queryParams.brandVo,
      typeId: queryParams.emparentIdVo ? parseInt(queryParams.emparentIdVo) : null,
      sonTypeId: queryParams.emsonIdVo ? parseInt(queryParams.emsonIdVo) : null,
      status: queryParams.statusVo !== '' ? parseInt(queryParams.statusVo) : null
    };
    const response = await httpInstance.post(
      `/eduservice/equipment/equipmentPage/${pagination.currentPage}/${pagination.pageSize}`,
      eqVo
    );
    equipmentList.value = response.data.list.map(item => ({
      ...item,
      userName: item.userName || '',
      salesman: item.salesman || '',
      salesmanId: item.salesmanId || '',
      isSpecial: item.isSpecial || false,
      equipmentImages: item.equipmentImages || []
    }));
    // 通过设备id到业务员设备关联表里查找业务员名称
    for (const item of equipmentList.value) {
      const res = await httpInstance.get(
        `/eduservice/businessmanEquipment/getBusinessmanById/${item.equipmentId}`
      );
      // 给业务员列表赋值
      if (res.data) {
        item.salesman = res.data.businessman?.name || '未知';
        item.salesmanId = res.data.businessman?.id || '未知';
      }
    }
    console.log(response.data);
    pagination.total = response.data.total;

  } catch (error) {
    ElMessage.error('获取设备列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取设备类型树形数据
const getTypeTreeData = async () => {
  try {
    const response = await httpInstance.get('/eduservice/equipmentType/getTypeTree');
    typeTreeData.value = response.data.data?.typeTree || [];
  } catch (error) {
    ElMessage.error('获取设备类型数据失败');
  }
};

// 获取业务员列表数据分页
const getBusinessmanList = async () => {
  businessmanLoading.value = true;
  try {
    // 构造查询参数
    const businessmanVo = {
      username: businessmanQuery.keyword,
      name: businessmanQuery.keyword // 假设后端支持按用户名或姓名搜索
    };

    const response = await httpInstance.post(
      `/eduservice/businessman/getBusinessmanPage/${businessmanPagination.currentPage}/${businessmanPagination.pageSize}`,
      businessmanVo
    );

    // 假设接口返回格式为 { list: [], total: 0 }
    businessmanList.value = response.data.list || [];
    businessmanPagination.total = response.data.total || 0;

  } catch (error) {
    ElMessage.error('获取业务员列表失败');
    console.error('业务员列表请求错误:', error);
  } finally {
    businessmanLoading.value = false;
  }
};

// 查询所有业务员
const getAllBusinessman = async () => {
  businessmanLoading.value = true;
  try {
    const response = await httpInstance.get('/eduservice/businessman/getAllBusinessman');
    allBusinessmanList.value = response.data.data.list;
  } catch (error) {
    ElMessage.error('获取所有业务员失败');
    console.error('所有业务员请求错误:', error);
  } finally {
    businessmanLoading.value = false;
  }
};

// 设备类型变更
const handleParentTypeChange = (value) => {
  queryParams.emparentIdVo = value;
  getEquipmentList();
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time.replace('T', ' '));
  if (isNaN(date.getTime())) return '';
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  getEquipmentList();
};

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  getEquipmentList();
};

// 业务员分页大小变化
const handleBusinessmanSizeChange = (size) => {
  businessmanPagination.pageSize = size;
  getBusinessmanList();
};

// 业务员当前页变化
const handleBusinessmanCurrentChange = (page) => {
  businessmanPagination.currentPage = page;
  getBusinessmanList();
};

// 审核操作
const handleAudit = (row) => {
  currentEquipment.value = row;
  auditForm.auditResult = 'pass';
  auditForm.auditRemark = '';
  auditForm.businessmanId = '';
  auditForm.appearanceDetection = '';
  auditForm.componentFunctionDetection = '';
  auditForm.performanceParameterDetection = '';
  auditForm.detectionConclusion = '';
  auditDialogVisible.value = true;
};

// 关闭审核对话框
const closeAuditDialog = () => {
  auditDialogVisible.value = false;
};

// 审核结果变更处理
const handleAuditResultChange = (value) => {
  // console.log('审核结果变更:', value);
};

// 提交审核
const submitAudit = async () => {
  if (!auditFormRef.value) return;
  
  await auditFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (auditForm.auditResult === 'pass') {
          await httpInstance.post(`/eduservice/equipment/audit/${currentEquipment.value.equipmentId}`, {
            status: 1,
          });     
          ElMessage.success('审核通过');
        } else {
          await httpInstance.post(`/eduservice/equipment/audit/${currentEquipment.value.equipmentId}`, {
            status: 0,
            auditRemark: auditForm.auditRemark
          });
          
          ElMessage.error('审核不通过');
        }
        
        const index = equipmentList.value.findIndex(item => item.equipmentId === currentEquipment.value.equipmentId);
        if (index !== -1) {
          equipmentList.value[index].status = auditForm.auditResult === 'pass' ? 1 : 0;
        }
        
        closeAuditDialog();
        getEquipmentList();
      } catch (error) {
        ElMessage.error('审核操作失败');
        console.error('审核错误:', error);
      }
    }
  });
};

// 上下架操作
const handleShelf = (row) => {
  const action = row.status === 1 ? '下架' : '上架';
  const newStatus = row.status === 1 ? 2 : 1;

  ElMessageBox.confirm(`确定要${action}【${row.brand}】设备吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    httpInstance.put(`/eduservice/equipment/shelf/${row.equipmentId}`, { status: newStatus })
      .then(() => {
        ElMessage.success(`${action}成功`);
        row.status = newStatus;
      })
      .catch(() => {
        ElMessage.error(`${action}失败`);
      });
  }).catch(() => {});
};

// 成交操作
const handleDeal = (row) => {
  ElMessageBox.confirm(`确定【${row.brand}】设备已成交吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'success'
  }).then(() => {
    httpInstance.post(`/eduservice/equipment/deal/${row.equipmentId}`, { status: 3 })
      .then(() => {
        ElMessage.success('标记成交成功');
        row.status = 3;
      })
      .catch(() => {
        ElMessage.error('标记成交失败');
      });
  }).catch(() => {});
};


// 查看详情
const handleDetail = (row) => {
  sessionStorage.setItem('equipment', JSON.stringify(row));
  router.push({ name: 'equipmentDetail' });
};

// 分配业务员 - 打开模态框
const handleAllocate = (row) => {
  // 当前设备是否审核
  if (row.status == 0) {
    ElMessage.warning('设备未审核通过，请先审核通过设备');
    return;
  }
  // 当前设备是否上架
  if (row.status == 2) {
    ElMessage.warning('设备未上架，请先上架设备');
    return;
  }
  // 当前设备是否已分配业务员
  if (row.businessmanId) {
    ElMessage.warning('设备已分配业务员，请勿重复分配');
    return;
  }
  currentAllocateEquipment.value = row;
  // 重置分页和查询条件
  businessmanPagination.currentPage = 1;
  businessmanQuery.keyword = '';
  // 加载业务员列表
  getBusinessmanList();
  // 显示模态框
  allocateDialogVisible.value = true;
};

// 确认分配
const confirmAllocate = async (businessman) => {
  try {
    ElMessageBox.confirm(`确定将设备【${currentAllocateEquipment.value.brand}】分配给业务员【${businessman.name}】吗？`, '确认分配', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      console.log(`设备【${currentAllocateEquipment.value.equipmentId}】`,"已分配给业务员",businessman);
      // 调用分配接口
      httpInstance.post(`/eduservice/businessmanEquipment/allocate/${currentAllocateEquipment.value.equipmentId}`, {
        businessmanId: businessman.businessmanId
      });
      ElMessage.success('分配成功');
    }).catch(() => {
      ElMessage.error('取消分配');
    });
    
    // 更新本地设备列表中的业务员信息
    const index = equipmentList.value.findIndex(
      item => item.equipmentId === currentAllocateEquipment.value.equipmentId
    );
    if (index !== -1) {
      equipmentList.value[index].salesmanId = businessman.id;
      equipmentList.value[index].salesman = businessman.name;
    }

    // 关闭模态框
    allocateDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('分配失败，请重试');
    console.error('分配错误:', error);
  }
};

// 关闭分配模态框
const closeAllocateDialog = () => {
  allocateDialogVisible.value = false;
};

// 删除
const handleDelete = (row) => {
  ElMessage.success('删除功能未完成');
};

// 砍价列表相关数据
const bargainDialogVisible = ref(false); // 砍价列表模态框显示状态
const currentBargainEquipment = ref(null); // 当前查看砍价列表的设备
const bargainList = ref([]); // 砍价记录列表
const bargainLoading = ref(false); // 砍价列表加载状态
const bargainPagination = reactive({ // 砍价列表分页参数
  currentPage: 1,
  pageSize: 5,
  total: 0
});

// 获取砍价状态文本
const getBargainStatusText = (status) => {
  switch (status) {
    case 0: return '待处理';
    case 1: return '已同意';
    case 2: return '已拒绝';
    default: return '未知状态';
  }
};

// 获取砍价状态样式
const getBargainStatusClass = (status) => {
  switch (status) {
    case 0: return 'status-pending'; // 待处理（黄色）
    case 1: return 'status-agreed'; // 已同意（绿色）
    case 2: return 'status-rejected'; // 已拒绝（红色）
    default: return 'status-unknown'; // 未知状态（灰色）
  }
};

// 打开砍价列表模态框
const handlePriceList = (row) => {
  currentBargainEquipment.value = row;
  bargainPagination.currentPage = 1; // 重置当前页
  getBargainList(); // 加载砍价列表
  bargainDialogVisible.value = true; // 显示模态框
};

// 获取砍价列表数据
const getBargainList = async () => {
  bargainLoading.value = true;
  try {
    // 构造查询参数（包含设备ID筛选）
    const response = await httpInstance.post(
      `/eduservice/bargainintention/getBargainIntentionList/${bargainPagination.currentPage}/${bargainPagination.pageSize}`,
    );
    
    // 处理返回数据
    bargainList.value = response.data.list || [];
    bargainPagination.total = response.data.total || 0;
    
    // 空数据提示
    if (bargainList.value.length === 0) {
      ElMessage.info(`【${currentBargainEquipment.value.brand}】暂无砍价记录`);
    }
  } catch (error) {
    ElMessage.error('获取砍价列表失败');
    console.error('砍价列表请求错误:', error);
  } finally {
    bargainLoading.value = false;
  }
};

// 关闭砍价列表模态框
const closeBargainDialog = () => {
  bargainDialogVisible.value = false;
  bargainList.value = []; // 清空列表
  bargainPagination.total = 0; // 重置总数
};

// 砍价列表分页大小变化
const handleBargainSizeChange = (size) => {
  bargainPagination.pageSize = size;
  getBargainList();
};

// 砍价列表当前页变化
const handleBargainCurrentChange = (page) => {
  bargainPagination.currentPage = page;
  getBargainList();
};

</script>

<style scoped>

.equipment-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 100px);
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
  font-weight: 600;
}

.operation-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
  flex-wrap: wrap;
}

.add-btn {
  margin-right: 10px;
  background-color: #1890ff;
}

.batch-btn {
  margin-right: 10px;
}

.export-btn {
  margin-right: 20px;
}

.filter-area {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  margin-left: auto;
}

.filter-select {
  width: 180px;
}

.search-input {
  width: 180px;
}

.equipment-table {
  width: 100%;
  margin-bottom: 20px;
  font-size: 14px;
}

.equipment-table .cell {
  padding: 8px 12px;
}

.head-image {
  width: 80px;
  height: 60px;
  border-radius: 4px;
}

.empty-image {
  width: 80px;
  height: 60px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.small-text {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
  line-height: 1.5;
}

.title-main {
  font-weight: 500;
  line-height: 1.5;
}

.price-text {
  color: #f5222d;
  font-weight: 500;
}

.contact-name {
  color: #1890ff;
}

.status-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.status-unaudit {
  color: #faad14;
}

.status-audited {
  color: #52c41a;
}

.status-online {
  color: #52c41a;
}

.status-offline {
  color: #f5222d;
}

.status-deal {
  color: #52c41a;
}

.status-undeal {
  color: #faad14;
}

.status-verified {
  color: #52c41a;
}

.status-unverified {
  color: #faad14;
}

.status-special {
  color: #f5222d;
}

.status-normal {
  color: #faad14;
}

.operate-btn {
  padding: 0;
  font-size: 12px;
  height: auto;
  color: #1890ff;
}

.text-online {
  color: #52c41a;
}

.text-offline {
  color: #f5222d;
}

.operation-buttons {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.text-detail {
  color: #1890ff;
}

.text-price {
  color: #fa8c16;
}

.text-allocate {
  color: #722ed1;
}

.text-edit {
  color: #13c2c2;
}

.pagination-container {
  text-align: right;
  margin-top: 20px;
}

/* 审核对话框样式 */
.equipment-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
  font-size: 14px;
}

.info-label {
  font-weight: bold;
  margin-right: 5px;
}

/* 分配业务员模态框样式 */
.allocate-search {
  margin-bottom: 15px;
}

.businessman-table {
  width: 100%;
  margin-bottom: 15px;
}

.businessman-pagination {
  text-align: right;
}
</style>